﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Speakup;
using WebLayer;
using System.Threading;
using System.ComponentModel;

namespace SpeakupUI
{
    class WebFetcherCompleteArgs : EventArgs
    {
        public ClassList Classes = null;
        public String Message;
    }


    class WebFetcher
    {
        private string User;
        private string Password;
        private string School;
        private Thread WebThread;
        private SynchronizationContext context;


        public WebFetcher(string user, string pass, string school)
        {
            User = user;
            Password = pass;
            School = school;

            context = SynchronizationContext.Current;
            if (context == null)
            {
                context = new SynchronizationContext();
            }
        }

        public void Fetch()
        {
            WebThread = new Thread(WebFetchThread);
            WebThread.Start();
        }

        public void Cancel()
        {
            if (WebThread != null)
            {
                WebThread.Abort();
            }

            WebFetcherCompleteArgs args = new WebFetcherCompleteArgs();
            args.Classes = null;
            args.Message = "Request was cancelled.";
            SendComplete(this, args);
        }

        public event EventHandler<WebFetcherCompleteArgs> Completed;
        
        void WebFetchThread()
        {
            string msg = null;            
            ClassList classes = null;

            try
            {
                LoginToken token = new LoginToken(User,Password,School);
                classes = ClassList.FetchFutureClasses(token);

                msg = "Ok.";
            }
            catch (UnauthorizedAccessException)
            {
                msg = "You provided invalid user/password/school values. Please correct them and retry.";
            }            
            catch (Exception ex)
            {
                msg = "Unknown error. \n" + ex.Message + "\n" + ex.StackTrace;
            }

            if (Completed != null)
            {
                WebFetcherCompleteArgs args = new WebFetcherCompleteArgs();
                args.Classes = classes;
                args.Message = msg;

                SendComplete(this, args);
            }
        }

        private void SendComplete(object sender, WebFetcherCompleteArgs args)
        {
            foreach (Delegate d in Completed.GetInvocationList())
            {
                SendOrPostCallback callback =  new SendOrPostCallback( delegate(object state)
                {
                    object[] rawArg = { sender, args };
                    d.DynamicInvoke(rawArg);
                });

                context.Post(callback, null);                
            }
        }



    }
}
